package com.example;

import com.example.utils.ConnectionFactoryUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/3/26 19:22
 **/
public class DeadLetterConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionFactoryUtils.getConnection();
        Channel channel = connection.createChannel();

        // 声明一个普通的交换机 和 队列 以及路由
        String exchangeName = "test_dlx_exchange";
        String routingKey = "dlx.#";
        String queueName = "test_dlx_queue";

        channel.exchangeDeclare(exchangeName, "topic", true, false, null);
        //指定死信发送的Exchange
        Map<String, Object> agruments = new HashMap<String, Object>();
        agruments.put("x-dead-letter-exchange", "dlx.exchange");
        //agruments.put("x-dead-letter-routing-key", "queue");
        //这个agruments属性，要设置到声明队列上
        channel.queueDeclare(queueName, true, false, false, agruments);
        channel.queueBind(queueName, exchangeName, routingKey);

        //要进行死信队列的声明
         channel.exchangeDeclare("dlx.exchange", "topic", true, false, null);
         channel.queueDeclare("dlx.queue", true, false, false, null);
         channel.queueBind("dlx.queue", "dlx.exchange", "");
        // headers={x-first-death-exchange=test_dlx_exchange, x-death=[{reason=expired, original-expiration=10000, count=1, exchange=test_dlx_exchange, time=Fri Mar 26 19:27:23 CST 2021, routing-keys=[dlx.save], queue=test_dlx_queue}], x-first-death-reason=expired, x-first-death-queue=test_dlx_queue}, delivery-mode=2, priority=null, correlation-id=null, reply-to=null, expiration=null, message-id=null, timestamp=null, type=null, user-id=null, app-id=null, cluster-id=null)
        channel.basicConsume("dlx.queue", true, new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.err.println("-----------consume message----------");
                System.err.println("consumerTag: " + consumerTag);
                System.err.println("envelope: " + envelope);
                System.err.println("properties: " + properties);
                System.err.println("body: " + new String(body));
            }
        });
    }
}
